To optimize the rendering of React list components, a unique identifier (UID) is required for each list item. This UID lets React identify the item
throughout its lifetime. To provide it, use the key
attribute of the list item. When the key
attribute is missing, React
will default to using the item’s index inside the list component. If the element ordering changes, it will cause keys to not match up between renders,
recreating the DOM. It can negatively impact performance and may cause issues with the component state.
function Blog(props) {
return (
<ul>
{props.posts.map((post) =>
<li> <!-- Noncompliant: When 'posts' are reordered, React will need to recreate the list DOM -->
{post.title}
</li>
)}
</ul>
);
}
To fix it, use a string or a number that uniquely identifies the list item. The key must be unique among its siblings, not globally.
If the data comes from a database, database IDs are already unique and are the best option. Otherwise, use a counter or a UUID generator.
Avoid using array indexes since, even if they are unique, the order of the elements may change.
function Blog(props) {
return (
<ul>
{props.posts.map((post) =>
<li key={post.id}> <!-- Compliant: id will always be the same even if 'posts' order changes -->
{post.title}
</li>
)}
</ul>
);
}